package com.goodmr.passport.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 验证码数据逻辑实现（redis）
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
@Service("verifyCodeRedisImpl")
class VerifyCodeRedisImpl implements VerifyCodeDao {

    private final static String VERIFY_CODE_CACHE_KEY = "goodmr:passport:receiver:%s";

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 生成随机验证码
     *
     * @param receiver 接收者标识
     * @param code     验证码
     * @param timeout  过期时间（s）s
     */
    @Override
    public void generate(String receiver, String code, long timeout) {

        String codeCacheKey = String.format(VERIFY_CODE_CACHE_KEY, receiver);
        redisTemplate.opsForValue().set(codeCacheKey, code, timeout, TimeUnit.SECONDS);
    }

    /**
     * 校验验证码是否正确
     *
     * @param receiver 接收者标识
     * @param code     验证码
     * @return boolean
     */
    @Override
    public boolean verify(String receiver, String code) {

        String codeCacheKey = String.format(VERIFY_CODE_CACHE_KEY, receiver);
        String signCode = redisTemplate.opsForValue().get(codeCacheKey);

        return code.equals(signCode);
    }

    /**
     * 删除随机验证码
     *
     * @param receiver 接收者标识
     */
    @Override
    public void remove(String receiver) {
        String codeCacheKey = String.format(VERIFY_CODE_CACHE_KEY, receiver);
        redisTemplate.delete(codeCacheKey);
    }
}
